package com.copro.chemdb.stat.rule.export;

import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.ExportRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;

public class Rule3C2 implements ExportRule {

	@SuppressWarnings("unchecked")
	@Override
	public void doExport(HSSFWorkbook wb, Subject subject, StatResult re,
			short customStyle, Application app) throws SimpleException {
		Map<String, Object> result = (Map<String, Object>) re.getResult();
		String text = (String) result.get("text");
		if (text.length() > 30) {
			text = text.substring(0, 30);
		}
		List<Subject> subjects = (List<Subject>) result.get("subjects");
		int count = ((Integer) result.get("count")).intValue();
		// create new sheet
		HSSFSheet sheet = wb.createSheet(text);
		HSSFRow row = sheet.createRow(0);
		CellUtil.createCell(row, 0, "有效记录数: " + count);
		// set the header
		row = sheet.createRow(1);
		HSSFRow row2 = sheet.createRow(2);
		CellUtil.createCell(row, 0, "单位名称", wb
				.getCellStyleAt((short) (customStyle + StyleHeader)));
		CellUtil.createCell(row, 1, "数据库名称", wb
				.getCellStyleAt((short) (customStyle + StyleHeader)));
		CellUtil.createCell(row, 2, text, wb
				.getCellStyleAt((short) (customStyle + StyleHeader)));
		sheet.addMergedRegion(new Region(1, (short) 0, 2, (short) 0));
		sheet.addMergedRegion(new Region(1, (short) 1, 2, (short) 1));
		sheet.addMergedRegion(new Region(1, (short) 2, 1, (short) (1 + subjects
				.size())));
		HSSFCellStyle styleHeader = wb.createCellStyle();
		styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		styleHeader.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
		for (int i = 0; i < subjects.size(); i++) {
			CellUtil.createCell(row2, i + 2, subjects.get(i).getBrief(),
					styleHeader);
		}
		// set the data body
		List<List<Object>> rows = (List<List<Object>>) result.get("rows");
		for (int i = 0; i < rows.size(); i++) {
			List<Object> cells = rows.get(i);
			row = sheet.createRow(i + 3);
			for (int j = 0; j < cells.size(); j++) {
				CellUtil.createCell(row, j, cells.get(j).toString());
			}
		}
	}

	@Override
	public void setup(Properties conf) {
	}

}
